﻿using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;

namespace Saber.Infrastructure.Logger
{
    
    public static class Log
    {
        public static string DirectoryName = "/Logs";

        private static StreamWriter sw;

        private static ReaderWriterLock _lock = new ReaderWriterLock();

        static Log()
        {

            string path = Constant.DataDirectory  + DirectoryName;
            string filename = path +"/"+ DateTime.Now.ToString("yyyy-MM-dd")+".txt";
            if (!Directory.Exists(path)){
                Directory.CreateDirectory(path);
            }
            if (!File.Exists(filename))
            {
                FileStream fs = File.Create(filename);
                fs.Close();
            }

            sw=new StreamWriter(filename,true,System.Text.Encoding.UTF8);
            sw.AutoFlush = true;

        }

        public static void _Log(string type, string message)
        {
            _lock.AcquireWriterLock(1000);
            sw.WriteLine(DateTime.Now.ToString("[ yyyy-MM-dd HH:mm:ss fff ] ") + type + " | " + message);
            _lock.ReleaseWriterLock();
        }


        /// <param name="message">example: "|prefix|unprefixed" </param>
        public static void Error(string message)
        {
            _Log("ERROR", message);    

        }

        /// <param name="message">example: "|prefix|unprefixed" </param>
        [MethodImpl(MethodImplOptions.Synchronized)]
        public static void Exception(string message, System.Exception e)
        {

            _Log("ERROR", message);
        
            _Log("ERROR", e.StackTrace);
        }
        
        /// <param name="message">example: "|prefix|unprefixed" </param>
        public static void Debug(string message)
        {
#if DEBUG
            _Log("DEBUG", message);    
#endif
        }

        /// <param name="message">example: "|prefix|unprefixed" </param>
        public static void Info(string message)
        {
            _Log("INFO ", message);        
        }

        /// <param name="message">example: "|prefix|unprefixed" </param>
        public static void Warn(string message)
        {
            _Log("WARN", message);         
        }
    }
}